package com.iuie.ns.system.shiro.filter;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.filter.authc.AuthenticationFilter;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.SavedRequest;

import com.iuie.ns.frame.servlet.ValidateCodeServlet;
import com.iuie.ns.frame.utils.MD5PasswordUtils;
import com.iuie.ns.frame.utils.StringUtils;
import com.iuie.ns.frame.utils.WebUtils;
import com.iuie.ns.system.service.loginlog.ISysLoginLogService;
import com.iuie.ns.system.service.user.ISysUserService;
import com.iuie.ns.system.vo.login.SysLoginLogVO;
import com.iuie.ns.system.vo.login.SysLoginLogVO.Builder;
import com.iuie.ns.system.vo.role.SysRoleVO;
import com.iuie.ns.system.vo.user.SysUserVO;

/**
 * 
 * @desc 自定义表单过滤器
 * @createTime 2017年6月11日 下午3:03:24
 * @author iuie
 */
public class MyFormAuthrnticationFilter extends FormAuthenticationFilter {
    
	@Resource
	private ISysUserService userService;
	
	@Resource
	private ISysLoginLogService loginLogService;
	
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {

		HttpServletRequest res = WebUtils.toHttp(request);
		String string = res.getParameter("captcha");
		if (string != null) {
			boolean flag = ValidateCodeServlet.validate(res, string);
			if (!flag){// 验证不成功，阻止进入不在登录认证
				request.setAttribute("shiroLoginFailure","randomCodeError");  
				return true;
			}
		}
		return super.onAccessDenied(request, response);
	}

	@Override
	protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response)
			throws Exception {
		Session session=subject.getSession();
		String userId=(String) token.getPrincipal();
	    SysUserVO user = userService.findByIdWithWhole(userId);
		session.setAttribute("user", user);
		String fallbackUrl = this.getSuccessUrl();
		String successUrl = null;
		SavedRequest savedRequest = WebUtils.getAndClearSavedRequest(request);
		if (savedRequest != null
				&& savedRequest.getMethod().equalsIgnoreCase(
						AccessControlFilter.GET_METHOD)) {
			successUrl = savedRequest.getRequestUrl();
		}
		if (!StringUtils.isEmpty(fallbackUrl) && !AuthenticationFilter.DEFAULT_SUCCESS_URL
						.equals(fallbackUrl)) {
			successUrl = ((HttpServletRequest) request).getContextPath()
					+ fallbackUrl;
		}
		if (successUrl == null) {
			successUrl = this.getSuccessUrl();
		}
		if (successUrl == null) {
			throw new IllegalStateException(
					"SuccessURLnotavailableviasavedrequestorviathe"
							+ "successUrlFallbackmethodparameter.Oneofthesemustbenon-nullfor"
							+ "issueSuccessRedirect()towork.");
		}
		
		// 记录登录日志
		Builder builder = new SysLoginLogVO.Builder();
		
		if (user.getCurrentRole() == null && user.getRoles().iterator().hasNext()) {
			SysRoleVO role = user.getRoles().iterator().next();
			if (role != null) {
				user.setCurrentRole(role);
			}
		}
		String loginRoleId = null;
		if (user.getCurrentRole() != null) {
			loginRoleId = user.getCurrentRole().getRoleId();
		}
		SysLoginLogVO log = builder.build(userId, loginRoleId, WebUtils.getIP(request));
		loginLogService.addOne(log);
		
		WebUtils.issueRedirect(request, response, successUrl,null,false);
		return false;
	}

	@Override
	protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
		String username = getUsername(request);
		String password = getPassword(request);
		String md5password = MD5PasswordUtils.encode(password);
		return createToken(username, md5password, request, response);
	}
	
}
